<?php

namespace app\admin\model\inventory;

use app\admin\model\outhouse\Kcmx;
use think\Db;
use think\Log;
use think\Model;
use app\admin\model\inventory\Wmskcview;
use app\admin\model\Kisapi;

class Wmskc extends Model
{
    // 表名
    protected $name = 'wms_kc';
    
    // 自动写入时间戳字段
   // protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        //'wh_type'
    ];
    
    //配置模型小数点格式化（去0补0）
    //要格式化的 字段=>方法
    protected $type = [
        'quantity'=>'quantity',
        'store_quantity' => 'quantity',
        'cur_quantity'=>'quantity',
        'iQuantity'=>'quantity',
        'fqty' => 'quantity'
    ];

    public function shelves(){
        return $this->hasOne('\app\common\model\Shelves','id','shelves_id',[],'left')->field('id,name,number')->setEagerlyType(0);
    }
    
    /**
     * 调拨单处理数据
     * @return void
     */
    public static function tbdjUpdataKc($data,$repeatKis = false)
    {
        //先减去原货架库存，再增
        //原货架减库存做日志
        self::OperateWmsKc($data, 'dec', 8,'调拨减库存',$repeatKis);

        //增加库存做日志
        unset($data['kc_id']);
        $data['shelves_id'] = $data['shelves_change_id'];
        $data['warehouse_id'] = $data['warehouse_change_id'];
        self::OperateWmsKc($data, 'inc', 88,'调拨增库存',$repeatKis);
    }

    /**
     * 采购更新库存
     * @param $data
     * @return void
     * @throws \think\Exception
     */
     public static function produreUpdateKc($data){
         //增加库存做日志
         $data['quantity'] = $data['iQuantity'];
         self::OperateWmsKc($data, 'inc', 1,'采购入库增库存');
     }
    /**
     * 领料单减少库存
     * @param $data
     * @return void
     */
    public static function materialUpdateKc($data){
        //减库存做日志
        $data['quantity'] = $data['iQuantity'];
        self::OperateWmsKc($data, 'dec', 2,'领料出库减库存');
    }

    /**
     * 其他入库出库库存操作
     * @param $warehouseCode
     * @param $shelvesId
     * @param $cInvCode
     * @param $iQuantity
     * @param $code
     * @param $code_date
     * @param $operation_type 1：增加库存，2:减少库存
     * @param $mx_type  5：其他入库，6：其他出库  、7上架出库 、8上架入库 9采购退回 10领料退回
     * @return void
     * @throws \think\Exception
     */
    public static function rdRecordUpdateKc($warehouseCode,$warehouse_id,$shelvesId,$createtime, $cInvCode, $iQuantity, $code, $code_date, $operation_type, $mx_type,$remark='')
    {
        //增加库存做日志
        $data = [
            'code' => $code,
            'order_code' => $code_date,
            'quantity' => $iQuantity,
            'inv_number' => $cInvCode,
            'warehouse_id' => $warehouse_id,
            'shelves_id' => $shelvesId,
        ];
        
        if($operation_type == 1){
            //增加库存做日志
            self::OperateWmsKc($data, 'inc', $mx_type,$remark);
        }else if($operation_type == 2){
            //减库存做日志
            if($mx_type==8){
                //调拨
                $data['kc_id'] = intval($remark);
                $remark = '调拨kc_id'.$remark;
            }
            self::OperateWmsKc($data, 'dec', $mx_type,$remark);
        }
    }
    
    //获取某仓库即时库存 读本地
    public static function getWmsKcCodes($warehouse_id = 0){
        $where = [
            'quantity' => ['GT',0]
        ];
        if($warehouse_id){
            $where['warehouse_id'] = $warehouse_id;
        }
        
        $inv_number_arr = self::where($where)
        ->distinct('inv_number')
        ->column('inv_number');
        
        //sqlsrv才需要
        /* if($inv_number_arr){
            $inv_number_arr = array_keys($inv_number_arr);
        } */
        return $inv_number_arr;
    }
    
    /*
     * 获取物料推荐仓库、货架，不用这个，直接在物料里面读，新增了2个字段 warehouse_name shelves_name
     *   */
    public static function getTjWhShID($inv_number,$warehouse_code = ''){
        $where = [
            'cInvCode' => $inv_number
        ];
        if ($warehouse_code){
            $where['cWhCode'] = $warehouse_code;
        }
        $where['shelves_id'] = ['neq','not null']; //不为空
        $kc = self::where($where)->field('id,shelves_id,warehouse_id')->find();
        if(!$kc){
            $kc = [
                'id' => '',
                'warehouse_id' => '',
                'shelves_id' => ''
            ];
        }
        return $kc;
    }
    
    /*
     * 获取库存相关
     * params 物料编码、仓库编码/id、货架编码/id  cBatch批号
     *   */
    public static function getWmskcinfo($inv_number,$warehouse_code_id,$shelves_code_id,$cBatch,$type=''){
        $inventory = [];
        $warehouse = [];
        $shelves = [];
        $kc = [];
        
        if($inv_number){
            $inventory = db('inventory')->where([
                'number' => $inv_number
            ])
            ->field('id,name,specification,unit,unit_code,store_unit,store_unit_code,
                    fCoefficient,classification_id,classification_name,ifshangjia')
            ->find();
        }
        
        if($warehouse_code_id){
            if(substr($warehouse_code_id, 0,1) == '0'){
                $where = ['number' => $warehouse_code_id];
            }else{
                if(stripos($warehouse_code_id,'.')){
                    $where = ['number' => $warehouse_code_id];
                }else{
                    $where = ['id' => $warehouse_code_id];
                }
            }
            
            $warehouse = db('warehouse')
            ->where($where)
            ->field('id,name,number')
            ->find();
        }
        
        if($warehouse){
            $where = [
                'number' => $shelves_code_id,
                'warehouse_id' => $warehouse['id']
            ];
            
            if(is_numeric($shelves_code_id)){
                unset($where['number']);
                $where['id'] = $shelves_code_id;
            }
            
            $shelves = db('shelves')
            ->where($where)
            ->field('id,name,number,type')
            ->find();
        }
        
        if($inv_number&&$warehouse&&$shelves){
            $where = [
                'inv_number'=>$inv_number,
                'warehouse_id'=> $warehouse['id'],
                'shelves_id' => $shelves['id'],
                'cBatch' => $cBatch
            ];
            if($type=='dec'){
                //扣除库存的，取有库存的记录
                $where['quantity'] = ['GT',0];
            }
            $kc = self::where($where)
            ->field('id,quantity,cur_quantity,fCoefficient')
            ->find();
        }
        
        return [$inventory,$warehouse,$shelves,$kc];
    }
    
    //增减库存 dec减  inc增
    /*
     * data数组必须包含 code、code_date、quantity inv_number shelves_id warehouse_id
     *   */
    public static function OperateWmsKc($data,$type='dec',$order_type,$remark='',$repeatKis = false){
        if($repeatKis){
            //重新发起金蝶回写，不更新本地库存
            return ;
        }

        if(!$data||!$order_type){
            exception('参数不能为空');
        }
        if($type!='dec'&&$type!='inc'){
            exception('增减类型参数错误');
        }
        
        $inv_number = '';
        if(!isset($data['kc_id'])&&!empty($data['kc_id'])){
            $kc = self::get($data['kc_id']);
            if($order_type==8){
                //调拨，原库存记录
                $data['warehouse_id'] = $kc['warehouse_id'];
                $data['shelves_id'] = $kc['shelves_id'];
            }
        }else{
            if(isset($data['cInvCode'])){
                $inv_number = $data['cInvCode'];
            }else{
                $inv_number = $data['inv_number'];
            }
            
            if(!$inv_number){
                exception('物料编码不能为空');
            }
            
            $wmskcInfo = self::getWmskcinfo($inv_number,$data['warehouse_id'],$data['shelves_id'],$data['cBatch'],$type);
            $kc = $wmskcInfo[3];
            if($type=='inc'&&!$kc){
                //增库存，找不到库存记录的，创建1条
                $inventory = $wmskcInfo[0];
                $warehouse = $wmskcInfo[1];
                $shelves = $wmskcInfo[2];
                
                if(!$inventory){
                    exception('找不到物料');
                }
                if(!$warehouse){
                    exception('找不到仓库');
                }
                if(!$shelves){
                    exception('找不到货架');
                }
                
                $kc = self::create([
                    'warehouse_id' => $data['warehouse_id'] ,
                    'warehouse_number' => $warehouse['number'],
                    'warehouse_name' => $warehouse['name'],
                    'inv_id' => $inventory['id'],
                    'inv_number' => $inv_number,
                    'inv_name' => $inventory['name'],
                    'inv_specification' => $inventory['specification'],
                    'inv_unit_code' => $inventory['unit_code'],
                    'inv_unit' => $inventory['unit'],
                    'inv_store_unit_code' => $inventory['store_unit_code'],
                    'inv_store_unit' => $inventory['store_unit'],
                    'fCoefficient' => $inventory['fCoefficient'],
                    'shelves_id' => $shelves['id'],
                    'shelves_number' => $shelves['number'],
                    'shelves_name' => $shelves['name'],
                    'shelves_type' => $shelves['type'],
                    'quantity' => 0,//默认0，再底下增
                    'cBatch' => $data['cBatch'],
                    'cur_quantity' => 0,
                    'classification_id' => $inventory['classification_id'],
                    'classification_name' => $inventory['classification_name'],
                    'createtime' => date('Y-m-d H:i:s',time())
                ]);
            }
        }
        
        $other_out_rflag = mb_substr($remark, 0,4,'utf-8');
        if ($order_type==4&&config('site.out_order_kc_flag')&&$other_out_rflag!='盘亏出库'){
            //其他出库，允许负库存，只记录库存明细，不操作库存，包括删除，逆向库存,盘点的出库照样执行
            $remark = '期初期间出库';
        }else{
            
            if(isset($data['quantity'])&&$data['quantity']<=0){
                exception('库存参数quantity异常');
            }

            if(!isset($kc->fCoefficient)){
                exception($inv_number.'库存参数fCoefficient异常或不存在库存');
            }

            //基础数量转常用数量
            $data['store_quantity'] = $data['quantity']/$kc->fCoefficient;//常用数量
            //$data['quantity'] = $data['quantity']*$kc->fCoefficient;//基本数量
            
            if($type == 'dec'){
                if(!$kc){
                    exception('物料编码:'.$inv_number.',出库找不到库存记录');
                }
                
                if($kc->quantity<$data['quantity']){
                    exception($type.'物料编码:'.$inv_number.'库存不足,请核实');
                }

                $kc->setDec('quantity',$data['quantity']);
                $kc->setDec('cur_quantity',$data['quantity']);
                $kc->save();
            }else{
                if(!$kc){
                    exception('物料编码:'.$inv_number.',入库找不到库存记录');
                }
                
                $kc->setInc('quantity',$data['quantity']);
                $kc->setInc('cur_quantity',$data['quantity']);
                $kc->save();
            }
        }
        
        //库存明细
        $kcmxData = [
            'code' => $data['code'],
            'code_date' => $data['code_date'],
            'iType' => $order_type,
            'iQuantity' => $data['quantity'],//基础
            'store_quantity' => $data['store_quantity'],//常用
            'cInvCode' => $inv_number,
            'cFree1' => isset($data['cFree1'])?$data['cFree1']:'',
            'cBatch' => $data['cBatch'],
            'shelves_id' =>$data['shelves_id'],
            'warehouse_id' => $data['warehouse_id'],
            'remark' => $remark,
            'type' => $type == 'dec'?0:1,//1加0减
            'createtime' => date('Y-m-d H:i:s',time())
        ];
        //Log::write($kcmxData,$type=='dec'?"减少库存":'增加库存');
        $kcmx = new Kcmx();
        $kcmx->save($kcmxData);
        //Kcmx::commonKcmxParams($data['code'],$data['code_date'],$data['quantity'],$inv_number,'',$data['shelves_id'],$data['warehouse_id'],$order_type,$remark);
    }
    
    //删除pda单据，逆向处理库存
    public static function deleteWmskcByPdaBillCode($billcode,$temp = ''){
        if(!$billcode){
            exception('删除库存，PDA单据号为空');
        }
        
        $kcmx = new Kcmx();
        $kcmx_rows = $kcmx::where('code',$billcode)->select();
        
        if(!$kcmx_rows){
            //exception('删除库存失败，PDA单据号'.$billcode.'找不到库存明细');
        }
        
        if($kcmx_rows){
            foreach ($kcmx_rows as $kcmx_row){
                $kcmx_row->kc_id = 0;
                $kcmx_row->quantity = $kcmx_row->iQuantity;
                $kcmx_row->code = '删'.$kcmx_row->code;
                if($kcmx_row['type']){//增
                    self::OperateWmsKc($kcmx_row,'dec',$kcmx_row->iType,'删单减库存');//减
                }else{//减
                    self::OperateWmsKc($kcmx_row,'inc',$kcmx_row->iType,'删单增库存');//增
                }
                //删除原库存明细
                $kcmx_row->where('id',$kcmx_row->id)->delete();
            }
        }
    }
    
    //检查库存，通过仓库id、货架id $returnFlag是否返回，false直接抛异常
    public static function checkKcByWhIDShID($warehouse_id,$shelves_id = 0){
        $where = [
            'warehouse_id' => $warehouse_id
        ];
        
        if($shelves_id){
            $where['shelves_id'] = $shelves_id;
        }
        
        return self::where($where)->value('id');
    }

    //获得金蝶广东味业账套，产品入库单，同步到wms成品仓（味业）库区中
    //成品仓ID7676	库区	03A04	成品区（味业）ID19
    public static function synKisProInDataToWMS($startDate='',$endDate=''){
        $now = date('Y-m-d',time());
        if(!$startDate){
            $startDate = $now;
            if(config('site.proInDateStart')){
                $startDate = config('site.proInDateStart');
            }
        }
        if(!$endDate){
            $endDate = $now;
            if(config('site.proInDateEnd')){
                $endDate = config('site.proInDateEnd');
            }
        }
        if($endDate<$startDate){
            return ;
        }

        $condition = [
            'PageSize'=>1,
            'PageIndex'=>1,
            "fTrantype" => 2,
            "fStatus" => "1",
            'fItemClassNm' => '4',
            'fAcctNum' => '001',//味业
            'StartTime' => $startDate,
            'EndTime' => $endDate.' 23:59:59'
        ];
        
        $row = Kisapi::getDataByName('getIcStockList',$condition,true);
        $count = 0;
        if(isset($row['data_totle'])){
            $count = $row['data_totle'];
        }
        
        if(!$count){
            //exception("已经最新数据，没有数据可以同步");
            return false;
        }
        
        $newList =[];
        if($count>1000) {
            for($i=1;$i<=(intval($count/1000)+1);$i++){
                 $condition['PageSize'] = 1000;
                 $condition['PageIndex'] = $i;
                 $data = Kisapi::getDataByName('getIcStockList',$condition,true);
                 $newList = array_merge($newList,$data);
            }
        }else{
            $condition['PageSize'] = 1000;
            $newList = Kisapi::getDataByName('getIcStockList',$condition,true);
        }
        
        if(empty($newList)||!isset($newList['data_item'])){
            //exception("已经最新数据，没有数据可以同步");
            return false;
        }
        
        $digits = getDigits();//小数点位数
        $temp_arr = [];
        
        if($newList){
            if(!count($newList['data_item'])) return ;//没数据，直接false
            foreach ($newList['data_item'] as $k=>$head) {
                $body = $head['icstockbillentry'];
                unset($head['icstockbillentry']);
                
                if(!$body){
                    continue;
                }
                
                foreach ($body as $value){
                    $check = db('kcmx')->where([
                        'code' => $head['fBillNo'],
                        'iType' => 23,
                        'cInvCode' => $value['fNumber'],
                        'cBatch' => $value['fBatchNo']
                    ])
                    ->value('id');

                    if($check){
                        continue;
                    }
                    
                    $kcData = [
                        'code'=>$head['fBillNo'],
                        'code_date'=>substr($head['fDate'],0,10),
                        'inv_number'=>$value['fNumber'],
                        'cBatch' => $value['fBatchNo'],
                        'quantity'=>$value['fQty'],//基本数量
                        'cFree1' => $value['fDetailID'],//表体 内码
                        'warehouse_id'=>7676,
                        'shelves_id'=>19
                    ];
                    //增库存
                    self::OperateWmsKc($kcData, 'inc', 23,'同步味业金蝶产品入库单');
                }
            }
        }
    }
}
